package sgd.tp2.server.net.tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import sgd.tp2.api.logging.Log;
import sgd.tp2.api.net.CDRFormatType;
import sgd.tp2.api.net.CEPType;
import sgd.tp2.server.net.Server;

public abstract class TCPServer extends Server {

	protected ServerSocket serverSocket = null;
	protected Socket socket = null;

	public TCPServer(CDRFormatType cdrFormatType, int port, CEPType cepType) {
		super(cdrFormatType, port, cepType);
	}

	@Override
	public void startServer() throws IOException {
		serverSocket = new ServerSocket(port);
		Log.infoln("Iniciado servidor TCP:{0} (Engine: {1}) com formato {2}.", port, cepType,
				cdrFormatType);

		try {
			Log.infoln("Espera coneccao do cliente...");
			socket = serverSocket.accept();
			Log.infoln("Cliente connectado com sucesso");
		} catch (IOException e) {
			if (serverSocket != null)
				Log.errorln("Escuta de mensagens nao concluida: {0}", e.getMessage());
			stopServer();
			return;
		}

		Log.info("A receber: ");
	}

	@Override
	public void stopServer() {

		if (serverSocket == null && socket == null)
			return;

		try {
			if (serverSocket != null && !serverSocket.isClosed())
				serverSocket.close();
			if (socket != null && !socket.isClosed())
				socket.close();

		} catch (IOException e) {
			Log.warningln("Nao foram fechadas as portas correctamente: {0}", e.getMessage());
		} finally {
			serverSocket = null;
			socket = null;
		}

		Log.infoln("Servidor terminado com sucesso.");
	}
}
